package com.jml.api.api.quickstart;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.QueueingConsumer;
import com.rabbitmq.client.QueueingConsumer.Delivery;

public class Consumer {

	public static void main(String[] args) throws Exception {
		//1 创建一个ConnectionFactory, 并进行配置
		ConnectionFactory connectionFactory = new ConnectionFactory();
		connectionFactory.setHost("192.168.150.138");
		connectionFactory.setPort(5672);
		connectionFactory.setVirtualHost("/");
		//2 通过连接工厂创建连接
		Connection connection = connectionFactory.newConnection();
		//3 通过connection创建一个Channel
		Channel channel = connection.createChannel();
		//4 声明（创建）一个队列
		String queueName = "test001";
		//第一个参数是队列名字
		//第二个参数true就是队列持久化,
		//第三个参数为true表示队列独占的方式这个队列只有一个channel去监听  可以保持顺序
		//第四个参数是如果队列脱离了路由就会自动删除
		//第五个是扩展参数
		channel.queueDeclare(queueName, true, false, false, null);
		//5 创建消费者
		QueueingConsumer queueingConsumer = new QueueingConsumer(channel);
		//6 设置Channel连接消费者
		//为true表示自动签收
		channel.basicConsume(queueName, true, queueingConsumer);
		while(true){
			//7 获取消息  这个方法没参数就会阻塞，参数为时间就表示有时间限制
			Delivery delivery = queueingConsumer.nextDelivery();
			String msg = new String(delivery.getBody());
			System.err.println("消费端: " + msg);
			//Envelope envelope = delivery.getEnvelope();
		}
	}
}
